import type {
  AnimalWithCharacter,
  AnimalWitCharacterNCuratorNShelter,
} from "@/app/animals/interfaces"
import type { FC } from "react"
import ImageGallery from "react-image-gallery"
import type { BadgeProps } from "@/shared/ui/badge"
import { Badge } from "@/shared/ui/badge"
import { GENDER_TO_TEXT, imageUrl } from "@/shared/lib"
import dayjs from "dayjs"
import { Link } from "react-router-dom"
import { Routes } from "@/shared/consts"
import { PawPrint } from "lucide-react"

type AnimalCardProps = { id: string | number } & (
  | (AnimalWithCharacter & {
      type: "search"
    })
  | (AnimalWitCharacterNCuratorNShelter & { type: "personal" })
)
const calculateAge = (date: string) => {
  const dateObj = dayjs(date)
  const now = dayjs()
  const months = Math.abs(dateObj.diff(now, "month"))
  const years = Math.abs(dateObj.diff(now, "year"))
  const monthsInYears = months % 12
  if (!years && !monthsInYears) return "меньше месяца"
  return `${years ? `${years} лет${monthsInYears ? ", " : ""}` : ""}${monthsInYears ? `${monthsInYears} месяцев` : ""}`
}

const useAnimalBadges = ({
  gender,
  breedName,
  characterIds,
  birthDate,
}: Pick<
  AnimalWitCharacterNCuratorNShelter,
  "gender" | "birthDate" | "characterIds"
> & { breedName?: string }): BadgeProps[] => {
  const res = [] as BadgeProps[]
  if (breedName) {
    res.push({ id: breedName, children: breedName })
  }
  if (birthDate) {
    res.push({ id: birthDate, children: calculateAge(birthDate) })
  }
  if (gender) {
    res.push({ id: gender, children: GENDER_TO_TEXT[gender] })
  }
  if (characterIds?.data) {
    characterIds?.data.reduce((acc, character) => {
      acc.push({
        id: String(character.id),
        variant: "light",
        children: character?.attributes?.name,
      })
      return acc
    }, res)
  }
  return res
}
export const AnimalPersonalCard = ({
  name,
  description,
  characterIds,
  gender,
  birthDate,
  photos,
  breed,
  shelter,
}: AnimalWitCharacterNCuratorNShelter) => {
  const badges = useAnimalBadges({
    breedName: breed?.data?.attributes?.name,
    gender,
    birthDate,
    characterIds,
  })
  const shelterLogo = shelter?.data?.attributes?.logo?.data?.attributes?.url
  const [...images] = photos?.data ?? []
  return (
    <div className="flex flex-col gap-3 pb-6">
      <h1 className="text-4xl font-medium">{name}</h1>
      <div className="flex flex-wrap gap-2">
        {badges.map(badge => (
          <Badge key={badge.id} {...badge} />
        ))}
      </div>
      {photos?.data ? (
        <div className="flex flex-wrap gap-2 max-w-full">
          <ImageGallery
            items={
              images?.map(image => ({
                original: imageUrl(image?.attributes?.url) ?? "",
                thumbnail:
                  imageUrl(image?.attributes?.formats.thumbnail.url) ?? "",
                originalClass:
                  "rounded-xl [&_img.image-gallery-image]:h-[320px] [&_img.image-gallery-image]:object-cover [&_.image-gallery-image]:object-center [&_.image-gallery-image]:rounded-xl overflow-hidden",
              })) ?? []
            }
            additionalClass="w-full [&_.image-gallery-thumbnails_.image-gallery-thumbnails-container]:text-left"
            showNav={false}
            showPlayButton={false}
            showFullscreenButton={false}
          />
        </div>
      ) : null}
      <div className="mt-3 rounded-xl bg-animalCard overflow-hidden p-3 flex gap-4">
        {shelterLogo ? (
          <img
            src={imageUrl(shelterLogo)}
            alt=""
            className="h-16 w-16 object-contain rounded-lg"
          />
        ) : (
          <PawPrint className="h-10 w-10" />
        )}
        <div className="flex flex-col gap-1">
          <p className="text-xs">Приют</p>
          <p className="text-sm">{shelter?.data?.attributes?.name}</p>
        </div>
      </div>
      <div className="flex flex-col gap-3">
        <h2 className="text-xl">Описание</h2>
        <p className="text-base">{description}</p>
      </div>
    </div>
  )
}

const AnimalSearchCard = ({
  name,
  description,
  characterIds,
  gender,
  birthDate,
  photos,
  breed,
  id,
}: AnimalWithCharacter & { id: string | number }) => {
  const breedName = breed?.data?.attributes?.name
  const badges = useAnimalBadges({
    breedName,
    birthDate,
    gender,
    characterIds,
  })
  return (
    <Link to={`${Routes.Dogs}/${id}`}>
      <div className="rounded-xl bg-animalCard overflow-hidden p-3 flex flex-col gap-4">
        {photos?.data ? (
          <img
            src={imageUrl(photos?.data?.[0]?.attributes?.url)}
            className="rounded-xl border-none border-transparent max-w-[240px] w-full h-[200px] object-cover"
            alt=""
          />
        ) : null}
        <div className="flex flex-col gap-3">
          <div className="flex flex-col gap-1">
            <h4 className="text-base font-medium">{name}</h4>
            <div className="flex flex-wrap gap-1">
              {badges.map(badge => (
                <Badge key={badge.id} {...badge} />
              ))}
            </div>
          </div>
          <p className="text-xs">{description}</p>
        </div>
      </div>
    </Link>
  )
}
const AnimalCard: FC<AnimalCardProps> = ({ type = "search", ...props }) => {
  const isPersonal = type === "personal"
  return (
    <>
      {isPersonal ? (
        <AnimalPersonalCard {...props} />
      ) : (
        <AnimalSearchCard {...props} />
      )}
    </>
  )
}
export default AnimalCard
